import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { inform_list, inform_delete, inform_add, inform_search } from '../utils/api'

//局校通知
export const useInformListStore = defineStore('informlist', () => {
  var tableData = ref([])
  var tableDatacopy = ref([])
  // const doubleCount = computed(() => count.value * 2)
  //保存tabledata数据
  function save_tableData() {
    inform_list().then((res) => {
      console.log('save', res.data)
      tableData.value = res.data.list
      tableDatacopy.value = res.data.list
    })
  }

  //删除局校通知数据
  function del_tableData(id) {
    inform_delete({ id }).then((res) => {
      console.log('删除后', res.data.list)
    })
    let i = tableData.value.findIndex((element) => {
      return element.id == id
    })
    tableData.value.splice(i, 1)
  }

  //添加局校通知数据
  function add_tableData(form) {
    let newdata = {}
    newdata.id = tableData.value.length + 1
    newdata.title = form.title
    newdata.content = form.desc
    newdata.scope = form.resource
    newdata.sendto = form.type.join('、')
    newdata.name = form.name
    //日期拼接
    let data = form.date1.getFullYear() + '-' + form.date1.getMonth() + '-' + form.date1.getDay() + ' ' + form.date2.getHours() + ':' + form.date2.getMinutes() + ':' + form.date2.getSeconds()
    newdata.datatime = data
    //将新增的通知加入到本地列表中
    tableData.value.push(newdata)
    console.log('tableData.value', tableData.value)
    //向服务器发请求
    inform_add(newdata).then((res) => {
      if (res.data.code == 200) {
        console.log(res.data)
      }
    })

  }
  //  查询局校通知数据
  function sea_tableData(searchText) {
    inform_search({ searchText }).then((res) => {
      console.log(res.data)
    })
    let newtableData = [];
    let temptableData = JSON.parse(JSON.stringify(tableData.value))
    if (searchText) {
      temptableData.filter((item) => {
        if ((item.title).includes(searchText)) {
          newtableData.push(item);
          return;
        }
      })
      tableData.value = newtableData
      console.log(newtableData)
    }

  }

  //  重置局校通知数据
  function res_tableData() {
    tableData.value = tableDatacopy.value
  }

  return { tableData, tableDatacopy, save_tableData, del_tableData, add_tableData, sea_tableData, res_tableData }
})
